package com.mbatis.produerConsumer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;

/**
 * 使用BlockingQueue实现生产者消费者
 * 阻塞队列 BlockingQueue 线程安全的
 */
public class PCTest3 {

    private static Integer count = 0;
    BlockingQueue blockingQueue = new ArrayBlockingQueue(10);

    public static void main(String[] args) {
        PCTest3 pcTest3 = new PCTest3();
        new Thread(pcTest3.new Producer()).start();
        new Thread(pcTest3.new Consumer()).start();
    }


    class Producer implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                try {
                    blockingQueue.put(1);
                    count++;
                    System.out.println(Thread.currentThread().getName() + "生产者生产,目前共有 " + count);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    class Consumer implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                try {
                    blockingQueue.take();
                    count--;
                    System.out.println(Thread.currentThread().getName() + "消费者消费，目前共有" + count);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
